<?php
/**
 * 下载图片
 * Class ImageSpider
 */
class ImageSpider
{
    private $code; // 状态码
    private $message; // 消息
    private $mode = 0777;//权限
    private $ds = ['\\', '/'];//路径符
    private $filename;//文件名
    private $ssl;//协议
    private $url;//图片地址
    private $file;//图片资源
    /**
     * 图片位置的根路径
     * @var string
     */
    private $base_path;

    /**
     * 图片对应的路径
     * @var string
     */
    private $image_path;

    /**
     * url对应的位置
     * @var string
     */
    private $url_path;

    public function __construct()
    {
        $this->url_path = self::is_https() . "://" . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"];
    }

    public function setFileName($file_name='')
    {
        $this->filename = $file_name;
        return $this;
    }

    /**
     * @param $url
     * @param string $path
     * @return string
     * @throws Exception
     */
    public function downloadImage($url, $path = '')
    {
        $path = self::pathHandle($path);//处理路径符兼容
        $this->base_path = __DIR__ . self::pathHandle($path); // 将传递的路径，主动拼接上根图片目录
        $this->url = $url;
        $this->image_path = $path;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在

        $file = curl_exec($ch);
        curl_close($ch);
        if ($file == false) {
            //  图片下载失败
            $this->code = -1;
            $this->message = '图片下载失败';
            return false;
        }else{
            $this->file = $file;
        }
        //  文件夹时需要添加 / 的
        if (substr($this->base_path, -1, 1) !== '/') {
            $this->base_path = $this->base_path . DIRECTORY_SEPARATOR;
        }
        $this->saveAsImage();
        return $this;
    }


    /**
     * 保存图片并返回url
     * @return string
     */
    private function saveAsImage()
    {
        $extension = pathinfo($this->url, PATHINFO_EXTENSION); //  获取图片后缀
        if(!$this->filename){
            $this->filename = uniqid(microtime(true)) . '.' . $extension; // 为图片生成唯一文件名
        }
        // 创建文件夹
        if (!is_dir($this->base_path)) mkdir($this->base_path, $this->mode, true);
        //资源存储
        $resource = fopen($this->base_path . $this->filename, 'w+');
        fwrite($resource, $this->file);
        fclose($resource);
        return $this;
    }

    /**
     * 路径符处理
     * @param string $path
     * @return string
     */
    private function pathHandle($path = '')
    {
        foreach ($this->ds as $v) $path = trim($path, $v);
        return DIRECTORY_SEPARATOR . $path;
    }

    /**
     * 判断当前协议是否为http|https
     * @return string
     */
    private function is_https()
    {
        if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            $this->ssl = 'https';
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            $this->ssl = 'https';
        } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            $this->ssl = 'https';
        }
        $this->ssl = 'http';
        return $this->ssl;
    }

    public function getFileName()
    {
        return $this->filename;
    }

    public function getCode()
    {
        return $this->code;
    }

    public function getMessage()
    {
        return $this->message;
    }

    public function getBasePath()
    {
        return str_replace($this->image_path,'',$this->base_path);
    }

    public function getImagePath()
    {
        return $this->base_path;
    }

    public function getFilePath()
    {
        return $this->base_path . $this->filename;
    }

    public function getUrlPath()
    {
        return $this->url_path . $this->image_path . DIRECTORY_SEPARATOR . $this->filename;
    }
}